import { createRouter, createWebHistory } from 'vue-router';
import LayOut from '../components/LayOut/index.vue';

const routes = [
  {
    path: '/',
    name: '/',
    redirect: '/Home',
    component: LayOut,
    children: [
      {
        path: '/Home',
        name: 'Home',
        component: () => import('@/views/HomeView/index.vue')
      },
      {
        path: '/FileUpload',
        name: 'FileUpload',
        component: () => import('@/views/FileUploadView/index.vue')
      }, {
        path: '/Diary',
        name: 'Diary',
        component: () => import('@/views/DiaryView/index.vue')
      }, {
        path: '/User',
        name: 'User',
        component: () => import('@/views/UserView/index.vue')
      }
    ]
  }, {
    path: '/Login',
    name: 'Login',
    component: () => import('@/views/LoginView/index.vue')
  }, {
    path: '/Register',
    name: 'Register',
    component: () => import('@/views/LoginView/register.vue')
  }, {
    path: '/404',
    name: '404',
    component: () => import('@/views/ErrorView/index.vue')
  }, {
    path: '/Upload/:parentId',
    name: 'Upload',
    component: () => import('@/components/Upload/index.vue')
  }, {
    path: '/User/FamilyMember',
    name: 'FamilyMember',
    component: () => import('@/views/UserView/familyMember.vue')
  }, {
    path: '/User/AlterUser/:id',
    name: 'AlterUser',
    component: () => import('@/views/UserView/alterUser.vue')
  }, {
    path: '/User/UserDetail/:id',
    name: 'UserDetail',
    component: () => import('@/views/UserView/userDetail.vue')
  }, {
    path: '/User/UserDetail/Avatars',
    name: 'Avatars',
    component: () => import('@/views/UserView/avatars.vue')
  }, {
    path: '/Diary/AddDiary',
    name: 'AddDiary',
    component: () => import('@/views/DiaryView/addDiary.vue')
  }
];
const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes,
});
//路由守卫，判断是否登录
router.beforeEach((to, from, next) => {
  // 获取token
  const token = localStorage.getItem('token');
  const currentTime = new Date().getTime();
  const loginTime = window.localStorage.getItem('loginTime');
  const bol = (currentTime - loginTime) > 86400000; //24h
  if (to.path == '/Login' || to.path == '/Register') {
    next();
  } else {
    // 如果没有token，或token过期，则跳转到登录页面
    if (bol) {
      ElMessage({
        message: '登录已过期，请重新登录',
        type: 'error',
        plain: true,
      });
      next('/Login');
    } else if (!token && to.path !== '/Login' && from.path !== '/Login') {
      next('/Login');
    } else {
      next();
    }
  }
});

export default router;
